package club.twelveblog.tblog.controller;

import club.twelveblog.tblog.common.constants.HttpStatusConstants;
import club.twelveblog.tblog.common.dto.Result;
import club.twelveblog.tblog.common.enums.ExceptionEnum;
import club.twelveblog.tblog.common.exception.BlogException;
import club.twelveblog.tblog.entity.Admin;
import club.twelveblog.tblog.entity.Category;
import club.twelveblog.tblog.entity.User;
import club.twelveblog.tblog.service.AdminService;
import club.twelveblog.tblog.service.UserService;
import club.twelveblog.tblog.utils.ResultGenerator;
import club.twelveblog.tblog.utils.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@RestController
@RequestMapping("tblog/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private UserService userService;
    @Autowired
    private Token token;
    @Autowired
    RedisTemplate redisTemplate;
    private Cookie cookie;

    /**
     * 根据管理员id查找管理员信息
     * @param admin_id
     * @return
     */
    @GetMapping("/{admin_id}")
    public Result<Admin> findAdminById(@PathVariable(name = "admin_id") Long admin_id){

        try {
            //使用JDK8新特性判断对象是否为空
            Optional<Admin> admin = adminService.findAdminById(admin_id);
            if(!admin.isPresent()){
                //如果admin.isPresent()返回true则对象不为空，否则返回false
                throw new BlogException(ExceptionEnum.ADMIN_NOT_FOUND);
            }
            return ResultGenerator.getResultByHttp(HttpStatusConstants.OK,admin.get());
        }catch (BlogException e){
            throw new BlogException(ExceptionEnum.ADMIN_NOT_FOUND);
        }
    }

    /**
     * 根据Admin修改昵称和密码
     * 前端传过来的Admin实体类必须包含admin_id、admin_nick_name、admin_password三个参数不能为空
     * @param admin
     * @return
     */
    @PatchMapping
    public Result upDateAdminInfo(Admin admin){
        if (StringUtils.isEmpty(admin.getAdmin_nick_name())||
                StringUtils.isEmpty(admin.getAdmin_password())
        ){
            throw new BlogException(ExceptionEnum.BAD_PARAM_REQUEST);
        }
        try {
            adminService.upDateAdminInfo(admin);
            return ResultGenerator.getResultByHttpNoData(HttpStatusConstants.UPDATE_SUCCESS);
        }catch (BlogException e){
            throw new BlogException(ExceptionEnum.UPDATE_FAILED);
        }
    }

    /**
     * 更新管理员头像url
     * @param admin
     */
    @PostMapping(value = "/updateAdminImg",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<String> updateAdminImg(Admin admin){
        try {
            adminService.updateAdminImg(admin);
            return ResponseEntity.status(HttpStatus.CREATED).body("头像更新成功!");
        }catch (BlogException e){
            throw new BlogException(ExceptionEnum.UPDATE_FAILED);
        }
    }

    /**
     * 添加分类
     * @param category
     * @return
     */
    @PostMapping("/addCategory")
    public ResponseEntity<String> addCategory(Category category){
        Category category1 = adminService.addCategory(category);
        if(category1==null){
            throw new BlogException(ExceptionEnum.ADD_FAILED);
        }
        return ResponseEntity.status(HttpStatus.CREATED).body("添加分类成功!");
    }

    /**
     * 查找所有用户
     * @param page
     * @return
     */
    @GetMapping("/findAllUser")
    public ResponseEntity<Page<User>> findAllUserByPage(@RequestParam(name = "page",defaultValue = "1") int page){
        Page<User> users = userService.findAllUserByPage(page);
//        long totalElements = users.getTotalElements();
//        int totalPages = users.getTotalPages();
        if (users.isEmpty()){
            throw new BlogException(ExceptionEnum.USERS_NOT_FOUND);
        }
//        System.out.println(totalPages);
        return ResponseEntity.status(HttpStatus.OK).body(users);
    }

    /**
     * 修改用户账号状态
     * @param user
     * @return
     */
    @PostMapping("/userStatus")
    public ResponseEntity<String> updateUserStatus(User user){
        userService.updateUserStatus(user);
        return ResponseEntity.status(HttpStatus.OK).body("更新成功");
    }

    @GetMapping("/test")
    public void test(){
        System.out.println("controller正在处理");
    }
    /**
     * 管理员登录模块
     */
    @PostMapping("adminLogin")
    public Result<String> adminLogin(@RequestParam String adminName, @RequestParam  String password, HttpServletResponse response){
        Admin admin=adminService.adminLogin(adminName,password);
        if (admin!=null){
            //向redis缓存登录成功数据
            String a=token.getToken(32);
            String b="admin";
            redisTemplate.opsForValue().set(a,b);
            //把token添加到cookie返回给客户端
            cookie=new Cookie("token",a);
            cookie.setHttpOnly(true);
            cookie.setPath("/");
            response.addCookie(cookie);
            return ResultGenerator.getResultByHttp(HttpStatusConstants.SUCCESS,"登录成功");
        }else {
            throw new  BlogException(ExceptionEnum.LOGIN_PASSWORD_FAILED);
        }

    }
    /**
     * 管理员注销模块
     */
    @GetMapping("logout")
    public Result<String> adminLogout(HttpServletResponse response, @CookieValue("token") String token){
        cookie.setValue("zhuxiao");

        response.addCookie(cookie);
        redisTemplate.delete(token);
        return ResultGenerator.getResultByHttp(HttpStatusConstants.SUCCESS,"注销成功");
    }
}
